package snafu.framework.states;

import java.util.ArrayList;
import java.util.List;

import snafu.framework.exceptions.SnafuException;
import snafu.framework.states.literals.StateLiteral;

public abstract class AbstractState implements State {
	
	@Override
	public <T, L extends StateLiteral<T>> T getLiteral(Class<L> clazz) {
		return getLiteral(clazz, null);
	}

	@Override
	public <T, L extends StateLiteral<T>> T getLiteral(Class<L> clazz, T defaultValue) {
		// search for all matching literals
		List<L> selectedLiterals = getLiterals(clazz);
		// if found at least one literal return first
		switch (selectedLiterals.size()) {
		case 0:
			return defaultValue;
		case 1:
			return selectedLiterals.get(0).getValue();
		default:
			throw new SnafuException("found more than one matching literal for " + clazz);
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public <L extends StateLiteral<?>> List<L> getLiterals(Class<L> clazz) {
		// select literals matching clazz
		List<L> stateLiterals = new ArrayList<L>();
		for (StateLiteral<?> literal : getLiterals()) {
			if (clazz.isAssignableFrom(literal.getClass())) {
				stateLiterals.add((L) literal);
			}
		}
		return stateLiterals;
	}

}
